<template>
  <div class="amap-wrapper">
    <div ref="mapContainer" class="amap-container" />
    <div class="search-box" v-if="showSearch">
      <el-select
        v-model="selectedLocation"
        filterable
        remote
        reserve-keyword
        placeholder="请输入地址关键词"
        :remote-method="handleSearchInput"
        :loading="loading"
        @change="handleLocationSelect"
      >
        <el-option
          v-for="item in searchResults"
          :key="item.id"
          :label="item.name"
          :value="item"
        >
          <span>{{ item.name }}</span>
          <span class="address-detail">{{ item.address }}</span>
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script setup>
import AMapLoader from '@amap/amap-jsapi-loader'
import { ElSelect, ElOption } from 'element-plus'

const MAP_CONFIG = {
  key: 'fea28d02f9ffd2050f90af8a744c6ba8',
  version: '2.0',
  plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.MapType', 'AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Geocoder', 'AMap.Driving'],
  serviceHost: 'https://webapi.amap.com'
}

const props = defineProps({
  center: {
    type: Array,
    default: () => [116.397428, 39.90923]
  },
  zoom: {
    type: Number,
    default: 13
  },
  viewMode: {
    type: String,
    default: '2D'
  },
  showSearch: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['location-selected', 'map-ready', 'map-clicked'])

const mapContainer = ref(null)
const map = ref(null)
const selectedLocation = ref(null)
const searchResults = ref([])
const loading = ref(false)
const markers = ref([])
const AMapClass = ref(null)
const placeSearchService = ref(null)
const searchCache = ref(new Map())
const CACHE_EXPIRE_TIME = 1000 * 60 * 30 // 缓存30分钟

// 初始化地图
const initMap = async () => {
  try {
    // 加载高德地图
    AMapClass.value = await AMapLoader.load(MAP_CONFIG)

    // 确保容器存在
    if (!mapContainer.value) return

    // 创建地图实例
    map.value = new AMapClass.value.Map(mapContainer.value, {
      zoom: props.zoom,
      center: props.center,
      viewMode: props.viewMode,
      resizeEnable: true,
      willReadFrequently: true,
      forceRender: false,
      optimizePanAnimation: true
    })

    // 添加控件
    map.value.addControl(new AMapClass.value.ToolBar())
    map.value.addControl(new AMapClass.value.Scale())
    map.value.addControl(new AMapClass.value.MapType())
    map.value.addControl(new AMapClass.value.Geolocation())

    // 初始化 PlaceSearch 服务
    AMapClass.value.plugin(['AMap.PlaceSearch'], () => {
      placeSearchService.value = new AMapClass.value.PlaceSearch({
        city: '全国',
        pageSize: 10,
        extensions: 'all',
        citylimit: false
      })
    })

    // 添加地图点击事件监听
    map.value.on('click', handleMapClick)

    emit('map-ready', map.value)
  } catch (error) {
    console.error('地图加载失败：', error)
  }
}

// 添加标记点
const addMarker = (options) => {
  if (!map.value || !AMapClass.value) return

  const marker = new AMapClass.value.Marker({
    map: map.value,
    position: options.position,
    title: options.title,
    icon: options.icon
  })

  markers.value.push(marker)
  return marker
}

// 清除所有标记点
const clearMarkers = () => {
  markers.value.forEach(marker => {
    marker.setMap(null)
  })
  markers.value = []
}

// 处理搜索输入
const handleSearchInput = async (query) => {
  if (!query || query.length < 1) {
    searchResults.value = []
    return
  }

  loading.value = true

  try {
    // 检查缓存
    const cachedResult = searchCache.value.get(query)
    if (cachedResult) {
      const { data, timestamp } = cachedResult
      // 检查缓存是否过期
      if (Date.now() - timestamp < CACHE_EXPIRE_TIME) {
        searchResults.value = data
        loading.value = false
        return
      } else {
        // 删除过期缓存
        searchCache.value.delete(query)
      }
    }

    const searchPromise = new Promise((resolve, reject) => {
      if (!placeSearchService.value) {
        AMapClass.value.plugin(['AMap.PlaceSearch'], () => {
          placeSearchService.value = new AMapClass.value.PlaceSearch({
            city: '全国',
            pageSize: 10,
            extensions: 'all',
            citylimit: false,
            autoFitView: true
          })
        })
      }

      placeSearchService.value.search(query, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          resolve(result.poiList?.pois || [])
        } else if (status === 'error') {
          reject(new Error(`搜索失败: ${result.info}`))
        } else if (status === 'no_data') {
          resolve([])
        } else {
          reject(new Error(`未知错误: ${status}`))
        }
      })
    })

    const pois = await searchPromise
    const processedResults = pois.map(poi => ({
      id: poi.id,
      name: poi.name,
      address: poi.address || '暂无详细地址',
      position: poi.location ? [poi.location.lng, poi.location.lat] : [],
      district: poi.adname || '',
      type: poi.type || '',
      tel: poi.tel || '',
      distance: poi.distance
    })).filter(item => item.position.length === 2)

    // 存储到缓存
    searchCache.value.set(query, {
      data: processedResults,
      timestamp: Date.now()
    })

    searchResults.value = processedResults

  } catch (error) {
    searchResults.value = []
  } finally {
    loading.value = false
  }
}

// 添加清理缓存的方法
const clearSearchCache = () => {
  const now = Date.now()
  for (const [key, value] of searchCache.value.entries()) {
    if (now - value.timestamp >= CACHE_EXPIRE_TIME) {
      searchCache.value.delete(key)
    }
  }
}

// 处理位置选择
const handleLocationSelect = async (selected) => {
  if (!selected || !map.value || !AMapClass.value) return

  const position = selected.position
  clearMarkers()

  addMarker({
    position,
    title: selected.name
  })

  selectedLocation.value = selected.name

  map.value.setCenter(position)
  map.value.setZoom(15)

  // 直接使用选中的数据发送事件
  emit('location-selected', {
    id: selected.id,
    name: selected.name,
    address: selected.address,
    location: position,
    type: selected.type,
    tel: selected.tel,
    distance: selected.distance
  })
}

// 路线规划
const planRoute = async (start, end) => {
  if (!AMapClass.value) return

  const driving = new AMapClass.value.Driving({
    map: map.value,
    panel: 'panel'
  })

  driving.search(
      new AMapClass.value.LngLat(start[0], start[1]),
      new AMapClass.value.LngLat(end[0], end[1])
  )
}

watch(() => props.center, (newCenter) => {
  if (map.value) {
    map.value.setCenter(newCenter)
  }
})

onMounted(() => {
  initMap()
  // 每10分钟清理一次过期缓存
  const cacheCleanInterval = setInterval(clearSearchCache, 1000 * 60 * 10)

  // 在组件卸载时清理定时器
  onUnmounted(() => {
    clearInterval(cacheCleanInterval)
  })
})

onUnmounted(() => {
  if (map.value) {
    map.value.destroy()
  }
})

defineExpose({
  map,
  addMarker,
  clearMarkers,
  planRoute
})

// 添加处理地图点击的函数
const handleMapClick = async (e) => {
  const lnglat = e.lnglat
  const position = [lnglat.getLng(), lnglat.getLat()]

  // 清除现有标记
  clearMarkers()

  // 添加新标记
  const marker = addMarker({
    position,
    title: '选中位置'
  })

  // 使用高德地图的地理编码服务获取位置详细信息
  const geocoder = new AMapClass.value.Geocoder()

  geocoder.getAddress(position, (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      const address = result.regeocode

      // 发送点击位置信息
      emit('map-clicked', {
        location: position,
        address: address.formattedAddress,
        addressComponent: address.addressComponent
      })
    }
  })
}
</script>

<style scoped>
.amap-wrapper {
  position: relative;
  width: 100%;
  height: 500px;
}

.amap-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
}

.search-box {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 100;
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  width: 300px;
}

.address-detail {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
  display: block;
}

</style>
